package com.dy.yunying.biz.controller.datacenter;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.dy.yunying.api.datacenter.dto.ActivityRechargeDataDto;
import com.dy.yunying.api.datacenter.vo.ActivityRechargeDataVO;
import com.dy.yunying.api.req.hongbao.HbActiveDataReq;
import com.dy.yunying.api.vo.hbdata.HbActiveCashConfigVo;
import com.dy.yunying.api.vo.hbdata.HbActiveHbDrawVo;
import com.dy.yunying.api.vo.hbdata.HbActiveVisitDetailVo;
import com.dy.yunying.api.vo.hbdata.HbFloatClickVo;
import com.dy.yunying.api.vo.hbdata.HbInvitePvVo;
import com.dy.yunying.api.vo.hbdata.HbMessageVo;
import com.dy.yunying.biz.service.datacenter.ActivityRechargeDataService;
import com.dy.yunying.biz.utils.DateUtils;
import com.dy.yunying.biz.utils.ExportUtils;
import com.dy.yunying.biz.utils.MapUtils;
import com.google.common.collect.Lists;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.exception.BusinessException;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import io.swagger.models.auth.In;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 *活跃付费明细查询
 * @author hma
 * @date 2022/9/05 10:29
 */
@Slf4j
@RestController("activityRecharge")
@RequestMapping("/dataCenter/activityRecharge")
@RequiredArgsConstructor
public class ActivityRechargeDataController {

	private final ActivityRechargeDataService activityRechargeDataService;


	/**
	 * 广告数据分析报表
	 *
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/count")
	public R countDataTotal(@Valid @RequestBody ActivityRechargeDataDto req) {

		return activityRechargeDataService.count(req);
	}


	/**
	 * 活跃付费明细数据列表 （汇总查询）
	 *
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/list")
	public R<List<ActivityRechargeDataVO>> list(@Valid @RequestBody ActivityRechargeDataDto req) {
		R<List<ActivityRechargeDataVO>> page = activityRechargeDataService.page(req);
		if (CommonConstants.FAIL.equals(page.getCode())){
			return page;
		}

		return page;
	}




	/**
	 * 活跃付费明细数据汇总
	 *
	 * @param req
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/collect")
	public R collect(@Valid @RequestBody ActivityRechargeDataDto req) {
		req.setSize(null);
		req.setCurrent(null);
		R<List<ActivityRechargeDataVO>> collect = activityRechargeDataService.collect(req);
		if (CommonConstants.FAIL.equals(collect.getCode())){
			return collect;
		}
		return collect;
	}


	/**
	 * 活跃付费明细数据导出
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/excelExport")
	public void export(@Valid @RequestBody  ActivityRechargeDataDto req, HttpServletResponse response, HttpServletRequest request) {
		try {
			List<ActivityRechargeDataVO> result = new ArrayList<>();
			String sheetName = "活跃付费明细表";
			req.setSize(9999999L);
			R<List<ActivityRechargeDataVO>> page = activityRechargeDataService.page(req);
			List<ActivityRechargeDataVO> list =page.getData();
			if (!CollectionUtils.isEmpty(list)){
				result.addAll(list);
			}
			R<List<ActivityRechargeDataVO>> collectResult = activityRechargeDataService.collect(req);
			List<ActivityRechargeDataVO> collectList =collectResult.getData();
			if (!CollectionUtils.isEmpty(collectList)){
				result.addAll(collectList);
			}
			List<String> headArr=Arrays.asList(req.getColumns().split(","));
			List<String> titleArr=Arrays.asList(req.getTitles().split(","));
			List<List<String>> headList = new ArrayList<>();
			for (int i = 0; i < titleArr.size(); i++) {
				//表头竖着写，会有组合表头，
				List<String> head = new ArrayList<>();
				head.add(titleArr.get(i));
				headList.add(head);
			}
			List<List<String>> valeList=Lists.newArrayList();
			//将值动态设置到list里面，按照表头顺序指定值存储
			for(ActivityRechargeDataVO vo:result){
				List<String> vList = new ArrayList<String>();
				for (int i = 0; i < headArr.size(); i++) {
					//数据是一行一行横着写
					vList.add(getValue(vo,headArr.get(i)));
				}
				valeList.add(vList);
			}
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			response.setCharacterEncoding("utf-8");
			String fileName = URLEncoder.encode("活跃付费明细表-"+ DateUtils.getCurrentTimeNoUnderline(), "UTF-8").replaceAll("\\+", "%20");
			response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
			response.setHeader("file-name", fileName);
			//设置excel宽度自适应
			ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
			// 创建sheet并设置动态标题
			WriteSheet detailSheet = EasyExcel.writerSheet(0, sheetName).head(headList).build();
			// 向sheet中写入数据，将值按照动态顺序进行处理后放入
			excelWriter.write(valeList, detailSheet);
			// 数据下载，完成后会自动关闭流
			excelWriter.finish();

		} catch (Exception e) {
			log.error("活跃付费明细数据导出异常：{}", e.getMessage());
			throw new BusinessException("活跃付费明细数据导出异常，请稍后重试");

		}


	}



	/**
	 * 动态获取字段值
	 *
	 * @param dto
	 * @param name
	 */
	private static String getValue(Object dto, String name) {
		try {
			Method[] m = dto.getClass().getMethods();
			for (int i = 0; i < m.length; i++) {
				if (("get" + name).toLowerCase().equals(m[i].getName().toLowerCase())) {
					return m[i].invoke(dto).toString() ;
				}
			}
		} catch (Exception e) {
			log.error("动态获取字段值失败：{}", e);
			return  null;
		}
		return null;
	}


}
